<template>
  <div>
    <h1>品牌列表</h1>
    <!-- 条件查询 -->
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请输入品牌名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-button type="primary" @click="onAddBrandShow">添加品牌</el-button>
      <el-button type="danger" @click="onDeleteBatch">批量删除</el-button>
    </div>
    <!-- 表格数据 -->
    <div style="margin-top: 10px">
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="brandId" label="品牌ID" width="70" />
        <el-table-column prop="brandName" label="品牌名称" width="120" />
        <el-table-column prop="brandTop" label="排序" width="80" />
        <el-table-column prop="brandUse" label="使用数量" width="80" />
        <el-table-column prop="brandStatus" label="状态" width="120">
          <template #default="scope">
            <el-switch
              v-model="scope.row.brandStatus"
              class="ml-2"
              inline-prompt
              active-text="显示"
              inactive-text="隐藏"
              :active-value="0"
              :inactive-value="1"
              @change="onChangeBrandStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" size="small" @click="onDelete(scope.row)"
              >删除</el-button
            >
            <el-button type="primary" size="small" @click="onEdit(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div style="margin-top: 10px">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[2, 4, 6]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 添加品牌---对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加品牌" width="500">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="品牌名称"
            :label-width="formLabelWidth"
            prop="brandName"
          >
            <el-input v-model="form.brandName" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="排序"
            :label-width="formLabelWidth"
            prop="brandTop"
          >
            <el-input-number v-model="form.brandTop" />
          </el-form-item>
          <el-form-item
            label="状态"
            :label-width="formLabelWidth"
            prop="brandStatus"
          >
            <el-radio-group v-model="form.brandStatus">
              <el-radio value="0">显示</el-radio>
              <el-radio value="1">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  getBrandList,
  addBrand,
  changeBrandStatus,
  deleteByBrandId,
  deleteBatchBrand,
} from "../api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

const tableData = ref([]);
const total = ref(0);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: "",
});

const onEdit = (row:any) => {
 console.log("onEdit",row);
}

//多选
const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

//批删
const onDeleteBatch = () => {
  if(multipleSelection.value==null || multipleSelection.value.length == 0){
    ElMessage.error("请选择要删除的品牌请选择要删除的品牌");
    return;
  }
  console.log("onDeleteBatch", multipleSelection.value);
  ElMessageBox.confirm("删除后无法恢复，确认删除所选数据吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteBatchBrand(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          loadBrandList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除取消",
      });
    });
};

//单删
const onDelete = (row: any) => {
  console.log("onDelete");
  ElMessageBox.confirm("删除后无法恢复，确认删除此项数据吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteByBrandId(row.brandId).then((res) => {
        if (res.data.code == 200) {
          ElMessage({
            type: "success",
            message: "删除成功",
          });
          loadBrandList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除取消",
      });
    });
};

const onChangeBrandStatus = (row: any) => {
  console.log("onChangeBrandStatus");
  changeBrandStatus(row).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("修改成功");
      loadBrandList();
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const ruleFormRef = ref<FormInstance>();
const form = ref({
  brandName: "",
  brandStatus: null,
  brandTop: null,
  brandUse: null,
});

const rules = reactive<FormRules<any>>({
  brandName: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
  brandTop: [{ required: true, message: "请输入排序", trigger: "blur" }],
  brandStatus: [{ required: true, message: "请选择状态", trigger: "change" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      onAddBrand();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogFormVisible.value = false;
};

const onAddBrand = () => {
  addBrand(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加品牌成功");
      loadBrandList();
      dialogFormVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const onAddBrandShow = () => {
  console.log("onAddBrandShow");
  form.value = {
    brandName: "",
    brandStatus: null,
    brandTop: null,
    brandUse: null,
  };
  dialogFormVisible.value = true;
};

//查询
const onQuery = () => {
  loadBrandList();
};

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadBrandList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadBrandList();
};

const loadBrandList = () => {
  getBrandList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      tableData.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};

onMounted(() => {
  loadBrandList();
});
</script>

<!-- 分页样式 -->
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>
<!-- 搜索样式 -->
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
